﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

namespace TK.Common.DataAnnotations
{
    /// <summary>
    /// 自定义枚举验证
    /// </summary>
    public class CustomEnumDataTypeAttribute : ValidationAttribute
    {
        /// <summary>
        /// ctor
        /// </summary>
        public CustomEnumDataTypeAttribute(Type enumType)
        {
            EnumType = enumType;
        }

        /// <summary>
        /// 最大值
        /// </summary>
        public Type EnumType { get; private set; }

        /// <summary>
        /// Determines whether the specified value of the object is valid.
        /// </summary>
        public override bool IsValid(object value)
        {
            if (value != null)
            {
                return GetDescriptionList(EnumType).Contains(value.ToString());
            }

            return true;
        }

        /// <summary>
        /// 获取枚举项列表
        /// </summary>
        private IList<string> GetDescriptionList(Type enumType)
        {
            var result = new List<string>();

            foreach (var enumVal in Enum.GetValues(enumType))
            {
                var description = enumVal.GetType().GetMember(enumVal.ToString())
                    .FirstOrDefault()?.GetCustomAttribute<DescriptionAttribute>()?.Description;

                result.Add(description ?? enumVal.ToString());
            }

            return result;
        }
    }
}
